package com.easybuilder.common.base.service.impl;

import com.easybuilder.common.base.entity.DynamicEntity;
import com.easybuilder.common.base.entity.SearchEntity;
import com.easybuilder.common.base.service.PageQuery;
import com.easybuilder.common.config.datasource.DataSourcePool;
import com.easybuilder.common.enums.DatabaseType;
import com.easybuilder.common.enums.RelationType;
import com.easybuilder.common.utils.DBUtil;
import com.easybuilder.common.utils.FileUtil;
import com.easybuilder.common.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Service
public class PageQueryImpl implements PageQuery {

    private static DatabaseType databaseType = DatabaseType.MYSQL;
    static {
        InputStream ins = FileUtil.getResourceStream("application.yml");
        Properties props = new Properties();
        try {
            props.load(ins);
            String driverClassName = props.getProperty("driverClassName");
            if (StringUtil.isNotEmpty(driverClassName)) {
                String driver = driverClassName.replaceAll(" ", "").toLowerCase();
                if (driver.indexOf("sqlserver") != -1) {
                    databaseType = DatabaseType.SQLSERVER;
                }
                if (driver.indexOf("oracle") != -1) {
                    databaseType = DatabaseType.ORACLE;
                }
                if (driver.indexOf("access") != -1) {
                    databaseType = DatabaseType.ACCESS;
                }
            }
            ins.close();
            System.out.println("当前数据库驱动：" + databaseType.name());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public PageResult getPage(SearchEntity searchEntity) {
        String tableName = searchEntity.getTableName();
        if (StringUtil.isEmpty(tableName)) {
            throw new RuntimeException("分页查询表名不能为空！");
        }
        StringBuilder sql = new StringBuilder("select * from ").append(tableName);
        //根据前端传递条件集合，生成sql条件语句
        String whereSql = DBUtil.resolveCriteria(searchEntity.getCriterias());
        sql.append(whereSql);
        //统计当前条件数据总量sql
        String countSql = sql.toString().replaceAll("\\*", "count(1)");
        //查询数据总量
        int total = DBUtil.countBySql(countSql);
        sql.append(getPageSql(searchEntity));
        //查询分页数据
        List<DynamicEntity> list = DBUtil.selectList(sql.toString());

        PageResult pageResult = new PageResult();
        pageResult.setPageNum(searchEntity.getPageNum());
        pageResult.setPageSize(searchEntity.getPageSize());
        pageResult.setTotal(total);
        pageResult.setData(list);
        return pageResult;
    }

    private String getPageSql(SearchEntity searchEntity) {
        int pageNum = searchEntity.getPageNum();
        int pageSize = searchEntity.getPageSize();
        String pageSql = "";
        //mysql分页（limit)
        if (getDatabaseType() == DatabaseType.MYSQL) {
            int start = pageNum * pageSize;
            int end = start + pageSize;
            pageSql = " limit " + start + "," + end;
        }
        //sqlserver分页（top）
        if (getDatabaseType() == DatabaseType.SQLSERVER) {

        }
        //oracle分页（rowNum）
        if (getDatabaseType() == DatabaseType.ORACLE) {

        }
        return pageSql;
    }

    //获取当前数据库类型
    private DatabaseType getDatabaseType() {

        return databaseType;
    }
}
